<template>
  <el-dialog
    :title="
      !dataForm.id ? i18n['gobal.button.insert'] : i18n['gobal.button.update']
    "
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item
        :label="i18n['sys.role.field.roleName.title']"
        prop="roleName"
      >
        <el-input v-model="dataForm.roleName" maxlength="64"></el-input>
      </el-form-item>
      <el-form-item :label="i18n['gobal.field.description']" prop="description">
        <el-input v-model="dataForm.description" maxlength="128"></el-input>
      </el-form-item>
      <el-form-item size="mini" :label="i18n['sys.role.field.menuList.title']">
        <el-tree
          :data="menuList"
          :props="menuListTreeProps"
          node-key="keyValue"
          ref="menuListTree"
          style="overflow: auto; max-height: 300px"
          :default-expand-all="true"
          show-checkbox
        >
        </el-tree>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{
        i18n["gobal.button.cancel"]
      }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{
        i18n["gobal.button.ok"]
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils";
export default {
  inject: ["i18n"],
  data() {
    return {
      visible: false,
      menuList: [],
      menuListTreeProps: {
        label: "menuName",
        children: "children",
      },
      dataForm: {
        id: 0,
        roleName: "",
        description: "",
      },
      dataRule: {
        roleName: [
          {
            required: true,
            message: i18n["sys.role.valid.roleName.not-null"],
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    init(id) {
      this.$http({
        url: this.$http.adornUrl("/menu/select"),
        method: "post",
        data: this.$http.adornData(),
      })
        .then(({ data }) => {
          this.menuList = treeDataTranslate(data.data, "keyValue");
        })
        .then(() => {
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
            this.$refs.menuListTree.setCheckedKeys([]);
          });
        })
        .then(() => {
          this.dataForm.id = id || 0;
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/role/info`),
              method: "post",
              data: this.$http.adornData({ key: this.dataForm.id }),
            }).then(({ data }) => {
              if (data && data.code === 200 && data.data) {
                this.dataForm.roleName = data.data.roleName;
                this.dataForm.description = data.data.description;

                this.refreshChecked(data.data.menuIdList);
              }
            });
          }
        });
    },
    // 遍历找出所有子节点来选中
    refreshChecked(datas) {
      datas.forEach((item) => {
        var node = this.$refs.menuListTree.getNode(item);
        if (node && node.isLeaf) {
          this.$refs.menuListTree.setChecked(node, true);
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/sys/role/${!this.dataForm.id ? "insert" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              roleId: this.dataForm.id || undefined,
              roleName: this.dataForm.roleName,
              description: this.dataForm.description,
              menuIdList: [].concat(
                this.$refs.menuListTree.getCheckedKeys(),
                this.$refs.menuListTree.getHalfCheckedKeys()
              ),
            }),
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: i18n["gobal.hint.succeeded"],
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  },
};
</script>
